<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--dict数据-->
      <el-col :span="7" :xs="24" class="grid-content">
        <div class="head-container">
          <el-row :gutter="10">
            <el-col :span="20">
              <el-input
                v-model="queryParams.dict.name"
                placeholder="请输入code/name名称"
                clearable
                size="small"
                prefix-icon="el-icon-search"
                @keyup.enter.native="getDictPage"
              />
            </el-col>
            <el-col :span="4">
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" />
            </el-col>
          </el-row>
        </div>
        <div class="head-container">
          <el-table
            ref="dictList"
            v-loading="loading.dict"
            :data="dictList"
            row-key="id"
            :show-header="false"
            fit
            highlight-current-row
            style="width: 100%;"
            @row-click="handleRow"
          >
            <el-table-column prop="name" align="center" label="name" />
            <el-table-column prop="typeCode" align="center" label="typeCode" />
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click.stop="handleUpdate(scope.row)"
                />
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click.stop="handleDelete(scope.row)"
                />
              </template>
            </el-table-column>
          </el-table>
          <div>
            <pagination
              :total="total.dict"
              :page.sync="queryParams.dict.current"
              :limit.sync="queryParams.dict.size"
              :pager-count="5"
              small
              layout="prev, pager, next,total"
              @pagination="getDictPage"
            />
          </div>
        </div>

      </el-col>

      <!-- 字典list数据 -->
      <el-col v-if="this.dict.typeCode != undefined && this.dict.type == 0" :span="17" :xs="24">
        <el-row>
          <el-form ref="queryListForm" :model="queryParams.list" :inline="true" label-width="68px">
            <el-form-item label="名称" prop="name">
              <el-input
                v-model="queryParams.list.name"
                placeholder="请输入名称"
                clearable
                size="small"
                style="width: 240px"
                @keyup.enter.native="getDictListList"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="getDictListList">搜索</el-button>
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleListAdd">新增</el-button>
            </el-form-item>
          </el-form>
        </el-row>
        <el-row :gutter="10" class="mb8">
          <el-table
            ref="dictListList"
            v-loading="loading.list"
            row-key="id"
            :data="dictListList"
            :key="'dictListList'"
            fit
            highlight-current-row
            style="width: 100%;"
          >
            <el-table-column prop="name" align="center" label="名称" />
            <el-table-column prop="value" align="center" label="值" />
            <el-table-column prop="label" align="center" label="标签" />
            <el-table-column label="操作" align="center">
              <template slot-scope="listScope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click.stop="handleListUpdate(listScope.row)"
                />
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click.stop="handleListDelete(listScope.row)"
                />
              </template>
            </el-table-column>
          </el-table>
          <div>
            <pagination
              :total="total.list"
              :page.sync="queryParams.list.current"
              :limit.sync="queryParams.list.size"
              @pagination="getDictListList"
            />
          </div>
        </el-row>
      </el-col>
      <!-- 字典Tree数据 -->
      <el-col v-if="this.dict.typeCode != undefined && this.dict.type == 1" :span="18" :xs="24">
        <el-form ref="queryTreeForm" :model="queryParams.tree" :inline="true" label-width="68px">
          <el-form-item label="名称" prop="name">
            <el-input
              v-model="queryParams.tree.name"
              placeholder="请输入用户名称"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="getDictTreeList"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="getDictTreeList">搜索</el-button>
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleTreeAdd">新增</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-table ref="dictTreeList" :data="dictTreeList" row-key="id" :key="'dictTreeList'" :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
            <el-table-column prop="name" align="center" label="名称名" :show-overflow-tooltip="true" width="160" />
            <el-table-column prop="value" align="center" label="值" />
            <el-table-column label="操作" align="center">
              <template slot-scope="treeScope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click.stop="handleTreeUpdate(treeScope.row)"
                />
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-plus"
                  @click="handleTreeAdd(treeScope.row)"
                />
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click.stop="handleTreeDelete(treeScope.row)"
                />
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </el-col>
    </el-row>

    <!-- 添加或修改字典配置对话框 -->
    <el-dialog :title="title.dict" :visible.sync="open.dict" width="500px" append-to-body>
      <el-form ref="form" :model="form.dict" :rules="rules.dict" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.dict.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="字典" prop="typeCode">
          <el-input v-model="form.dict.typeCode" :disabled="form.dict.id != undefined" placeholder="请输入字典类型" />
        </el-form-item>
        <el-form-item label="系统级别" prop="system">
          <el-select v-model="form.dict.system" placeholder="请选择"  style="width: 100%;">
            <el-option
              v-for="item in systemDict"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.dict.type" placeholder="请选择"  style="width: 100%;">
            <el-option
              v-for="item in typeDict"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.dict.remarks" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改字典List配置对话框 -->
    <el-dialog :title="title.list" :visible.sync="open.list" width="500px" append-to-body>
      <el-form ref="formList" :model="form.list" :rules="rules.list" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.list.name" placeholder="请输入中文名称" />
        </el-form-item>
        <el-form-item label="值" prop="value">
          <el-input v-model="form.list.value" placeholder="请输入对应值" />
        </el-form-item>
        <el-form-item label="标签" prop="label">
          <el-tag
            v-for="tag in form.list.dynamicTags"
            :key="tag"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)"
          >
            {{ tag }}
          </el-tag>
          <el-input
            v-if="form.list.inputVisible"
            ref="saveTagInput"
            v-model="form.list.inputValue"
            class="input-new-tag"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          />
          <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
        </el-form-item>
        <el-form-item label="显示排序" prop="sort">
          <el-input-number v-model="form.list.sort" style="width: 100%;" :min="0" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.list.remarks" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitListForm">确 定</el-button>
        <el-button @click="cancelList">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改字典Tree配置对话框 -->
    <el-dialog :title="title.tree" :visible.sync="open.tree" width="500px" append-to-body>
      <el-form ref="formTree" :model="form.tree" :rules="rules.tree" label-width="80px">
        <el-form-item label="父级">
          <el-cascader
            v-model="form.tree.treePids"
            :props="treeProps"
            :options="form.tree.treeOptions"
            filterable
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.tree.name" placeholder="请输入中文名称" />
        </el-form-item>
        <el-form-item label="值" prop="value">
          <el-input v-model="form.tree.value" placeholder="请输入对应值" />
        </el-form-item>
        <el-form-item label="显示排序" prop="sort">
          <el-input-number v-model="form.tree.sort" style="width: 100%;" :min="0" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.tree.remarks" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitTreeForm">确 定</el-button>
        <el-button @click="cancelTree">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import { handleTree } from '@/utils'
import { getDictPage, getDict, updateDict , saveDict, delDict} from '@/api/admin/sysDict'
import { getDictListList, getDictList, updateDictList , saveDictList, delDictList} from '@/api/admin/sysDictList'
import { getDictTreeList, getDictTreeTree, getDictTree , updateDictTree, saveDictTree, delDictTree} from '@/api/admin/sysDictTree'
export default {
  name: 'Dict',
  components: { Pagination },
  data() {
    return {
      // 弹出层标题
      title: {
        dict: '',
        list: '',
        tree: ''
      },
      treeProps: { checkStrictly: true, value: 'id', label: 'name' },
      // 遮罩层
      loading: {
        dict: true,
        list: true,
        tree: true
      },
      dict: {
        type: 0,
        typeCode: undefined
      },
      // 用户数据
      dictList: [],
      dictListList: [],
      dictTreeList: [],
      // 总数量
      total: {
        dict: 0,
        list: 0,
        tree: 0
      },
      // 是否显示弹出层
      open: {
        dict: false,
        list: false,
        tree: false
      },
      // 查询参数
      queryParams: {
        dict: {
          current: 1,
          size: 10,
          typeCode: undefined
        },
        list: {
          current: 1,
          size: 10,
          typeCode: undefined,
          name: undefined
        },
        tree: {
          typeCode: undefined
        }
      },
      // 表单参数
      form: {
        dict: {
        },
        list: {
          typeCode: undefined,
          dynamicTags: [],
          inputVisible: false,
          inputValue: ''
        },
        tree: {
          typeCode: undefined
        }
      },
      systemDict: [{
        value: 1,
        name: '是'
      },
      {
        value: 0,
        name: '否'
      }],
      typeDict: [{
        value: 1,
        name: '树形'
      },
      {
        value: 0,
        name: '列表'
      }],
      // 表单校验
      rules: {
        dict: {
          name: [
            { required: true, message: '名称不能为空', trigger: 'blur' }
          ],
          typeCode: [
            { required: true, message: '字典类型不能为空', trigger: 'blur' }
          ]
        },
        list: {
          name: [
            { required: true, message: '名称不能为空', trigger: 'blur' }
          ],
          value: [
            { required: true, message: '值不能为空', trigger: 'blur' }
          ],
          sort: [
            { required: true, message: '顺序不能为空', trigger: 'blur' }
          ]
        },
        tree: {
          name: [
            { required: true, message: '名称不能为空', trigger: 'blur' }
          ],
          value: [
            { required: true, message: '值不能为空', trigger: 'blur' }
          ],
          sort: [
            { required: true, message: '顺序不能为空', trigger: 'blur' }
          ]
        }
      }
    }
  },
  created() {
    this.getDictPage()
  },
  methods: {
    /** 查询字典列表 */
    getDictPage() {
      return new Promise((resolve, reject) => {
        getDictPage(this.queryParams.dict)
          .then((res) => {
            const { data } = res
            this.dictList = data.records
            this.total.dict = data.total
            this.loading.dict = false
            resolve(data.records)
          })
          .catch((err) => {
            console.log('失败' + err)
          })
      }).then((data) => {
        this.$refs.dictList.setCurrentRow(this.dictList[0])
        this.handleRow(this.dictList[0])
      })
    },
    /** 查询字典list列表 */
    getDictListList() {
      this.dictListList = []
      getDictListList(this.queryParams.list)
        .then((res) => {
          const { data } = res
          this.dictListList = data.records
          this.total.list = data.total
          this.loading.list = false
        })
        .catch((err) => {
          console.log('失败' + err)
        })
    },
    /** 查询字典tree列表 */
    getDictTreeList() {
      this.dictTreeList = []
      getDictTreeTree(this.queryParams.tree)
        .then(res => {
          const { data } = res
          this.dictTreeList = handleTree(data)
          console.log(this.dictTreeList)
          this.loading.tree = false
        })
        .catch(err => {
          console.log('失败' + err)
        })
    },
    /** 查询字典tree列表 */
    getDictTreeTree(extId) {
      this.form.tree.treeOptions = []
      getDictTreeTree({
        typeCode: this.form.tree.typeCode,
        extId: extId })
        .then(res => {
          const { data } = res
          const dict = { id: '0', name: '主类目', children: [] }
          dict.children = handleTree(data)
          this.form.tree.treeOptions = [dict]
        })
        .catch((err) => {
          console.log('失败' + err)
        })
    },
    /** 选中行 */
    handleRow(row, event, column) {
      if(this.dict.typeCode == row.typeCode) {
        return 
      }
      this.dictListList = []
      this.dictTreeList = []
      if (row.type == 0) {
        this.dict.typeCode = row.typeCode
        this.dict.type = 0
        this.form.list.typeCode = row.typeCode
        this.queryParams.list.typeCode = row.typeCode
        this.form.tree.typeCode = undefined
        this.getDictListList()
      } else {
        this.dict.typeCode = row.typeCode
        this.dict.type = 1
        this.form.tree.typeCode = row.typeCode
        this.queryParams.tree.typeCode = row.typeCode
        this.form.list.typeCode = undefined
        this.getDictTreeList()
      }
      console.log(this.dict)
    },
    handleClose(tag) {
      this.form.list.dynamicTags.splice(this.form.list.dynamicTags.indexOf(tag), 1)
    },
    showInput() {
      this.form.list.inputVisible = true
      this.$nextTick(_ => {
        console.log(this.$refs)
        this.$refs['saveTagInput'].input.focus()
      })
    },
    handleInputConfirm() {
      const inputValue = this.form.list.inputValue
      if (inputValue) {
        this.form.list.dynamicTags.push(inputValue)
      }
      this.form.list.inputVisible = false
      this.form.list.inputValue = ''
    },

    // 取消按钮
    cancel() {
      this.open.dict = false
      this.reset()
    },
    // 取消List按钮
    cancelList() {
      this.open.list = false
      this.reset()
    },
    // 取消Tree按钮
    cancelTree() {
      this.open.tree = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        dict: {
          id: undefined,
          name: undefined,
          typeCode: undefined,
          type: 0,
          system: 0,
          remarks: undefined
        },
        list: {
          id: undefined,
          sort: 10,
          name: undefined,
          value: undefined,
          label: undefined,
          remarks: undefined,
          typeCode: this.dict.typeCode,
          dynamicTags: [],
          inputVisible: false,
          inputValue: ''
        },
        tree: {
          id: undefined,
          parentId: undefined,
          sort: 10,
          name: undefined,
          value: undefined,
          remarks: undefined,
          typeCode: this.dict.typeCode,
          treePids: ['0'],
          treeOptions: []
        }
      }
      this.$nextTick(()=>{
        this.$refs['form'] && this.$refs['form'].clearValidate && this.$refs['form'].clearValidate();
      })
      this.$nextTick(()=>{
         this.$refs['formList'] && this.$refs['formList'].clearValidate && this.$refs['formList'].clearValidate();
      })
      this.$nextTick(()=>{
         this.$refs['formTree'] && this.$refs['formTree'].clearValidate && this.$refs['formTree'].clearValidate();
      })
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset()
      this.open.dict = true
      this.title.dict = '添加字典'
    },
    /** 新增List按钮操作 */
    handleListAdd(row) {
      this.reset()
      this.open.list = true
      this.title.list = '添加字典'
    },
    /** 新增Tree按钮操作 */
    handleTreeAdd(row) {
      this.reset()
      this.getDictTreeTree('')
      if (row.id) {
        this.form.tree.treePids = row.parentIds.substring(0, row.parentIds.length - 1).split(',')
        this.form.tree.treePids.push(row.id)
      }
      this.open.tree = true
      this.title.tree = '添加字典'
    },
    /** 删除按钮操作 */
    delDict(id) {
      delDict(id).then(() => {
        this.getDictPage()
        this.msg('删除成功')
      })
    },
    /** 删除按钮操作 list */
    delDictList(id) {
      delDictList(id).then(() => {
        this.getDictListList()
        this.msg('删除成功')
      })
    },
    /** 删除按钮操作 tree */
    delDictTree(id) {
      delDictTree(id).then(() => {
        this.getDictTreeList()
        this.msg('删除成功')
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      getDict(row.id)
        .then((res) => {
          const { data } = res
          this.form.dict = data
          this.open.dict = true
          this.title.dict = '修改字典'
        })
        .catch((err) => {
          console.log('失败' + err)
        })
    },
    /** 修改字典list按钮操作 */
    handleListUpdate(row) {
      this.reset()
      getDictList(row.id)
        .then((res) => {
          const { data } = res
          this.form.list.id = data.id
          this.form.list.name = data.name
          this.form.list.value = data.value
          this.form.list.sort = data.sort
          this.form.list.remarks = data.remarks
          if (data.label) {
            this.form.list.dynamicTags = data.label.split(',')
          }
          this.open.list = true
          this.title.list = '修改字典'
        })
        .catch((err) => {
          console.log('失败' + err)
        })
    },
    /** 修改字典list按钮操作 */
    handleTreeUpdate(row) {
      this.reset()
      this.getDictTreeTree(row.id)
      getDictTree(row.id)
        .then((res) => {
          const { data } = res
          this.form.tree.id = data.id
          this.form.tree.parentId = data.parentId
          this.form.tree.name = data.name
          this.form.tree.value = data.value
          this.form.tree.sort = data.sort
          this.form.tree.remarks = data.remarks
          console.log(data)
          this.form.tree.treePids = data.parentIds.substring(0, data.parentIds.length - 1).split(',')
          this.open.tree = true
          this.title = '修改字典'
        })
        .catch((err) => {
          console.log('失败' + err)
        })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.dict.id !== undefined) {
            updateDict(this.form.dict).then(res => {
              this.msg('修改成功')
              this.open.dict = false
              this.getDictPage()
            })
          } else {
            saveDict(this.form.dict).then(res => {
              this.msg('新增成功')
              this.open.dict = false
              this.getDictPage()
            })
          }
        }
      })
    },
    /** 提交List按钮 */
    submitListForm: function() {
      this.$refs['formList'].validate(valid => {
        if (valid) {
          this.form.list.label = this.form.list.dynamicTags.join(',')
          if (this.form.list.id !== undefined) {
            updateDictList(this.form.list).then(res => {
              this.msg('修改成功')
              this.open.list = false
              this.getDictListList()
            })
          } else {
            saveDictList(this.form.list).then(res => {
              this.msg('新增成功')
              this.open.list = false
              this.getDictListList()
            })
          }
        }
      })
    },
    /** 提交Tree按钮 */
    submitTreeForm: function() {
      this.$refs['formTree'].validate(valid => {
        if (valid) {
          this.form.tree.parentId =  this.form.tree.treePids[this.form.tree.treePids.length - 1]
          if (this.form.tree.id !== undefined) {
            updateDictTree(this.form.tree).then(res => {
              this.msg('修改成功')
              this.open.tree = false
              this.getDictTreeList()
            })
          } else {
            saveDictTree(this.form.tree).then(res => {
              this.msg('新增成功')
              this.open.tree = false
              this.getDictTreeList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除名称为"' + row.typeCode + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.delDict(row.id)
      })
    },
    /** 删除List按钮操作 */
    handleListDelete(row) {
      this.$confirm('是否确认删除名称为"' + row.name + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.delDictList(row.id)
      })
    },
    /** 删除Tree按钮操作 */
    handleTreeDelete(row) {
      this.$confirm('是否确认删除名称为"' + row.name + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.delDictTree(row.id)
      })
    }
  }
}
</script>
<style>
  .grid-content {border-right:1px}
</style>
